import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/settings_provider.dart';

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设置'),
      ),
      body: Consumer<SettingsProvider>(
        builder: (context, settings, child) {
          return ListView(
            children: [
              // 基本设置
              _buildSection(
                context,
                '基本设置',
                [
                  ListTile(
                    title: const Text('设备名称'),
                    subtitle: Text(settings.deviceName),
                    onTap: () => _showDeviceNameDialog(context),
                  ),
                  ListTile(
                    title: const Text('自动关闭时间'),
                    subtitle: Text('${settings.autoOffMinutes} 分钟'),
                    onTap: () => _showAutoOffDialog(context),
                  ),
                  ListTile(
                    title: const Text('主题'),
                    subtitle: Text(_getThemeModeName(settings.themeMode)),
                    onTap: () => _showThemeModeDialog(context),
                  ),
                  SwitchListTile(
                    title: const Text('过渡动画'),
                    subtitle: const Text('切换时使用渐变效果'),
                    value: settings.useTransition,
                    onChanged: (value) => settings.setUseTransition(value),
                  ),
                ],
              ),

              // 高级设置
              _buildSection(
                context,
                '高级设置',
                [
                  ListTile(
                    title: const Text('渐变持续时间'),
                    subtitle: Text('${settings.transitionDuration.toInt()} 毫秒'),
                    onTap: () => _showTransitionDurationDialog(context),
                  ),
                  ListTile(
                    title: const Text('亮度范围'),
                    subtitle: Text('${(settings.minBrightness * 100).toInt()}% - ${(settings.maxBrightness * 100).toInt()}%'),
                    onTap: () => _showBrightnessRangeDialog(context),
                  ),
                  ListTile(
                    title: const Text('色温范围'),
                    subtitle: Text('${(settings.minColorTemp * 100).toInt()}% - ${(settings.maxColorTemp * 100).toInt()}%'),
                    onTap: () => _showColorTempRangeDialog(context),
                  ),
                  SwitchListTile(
                    title: const Text('记住上次设置'),
                    subtitle: const Text('下次启动时恢复上次的设置'),
                    value: settings.rememberLastSettings,
                    onChanged: (value) => settings.setRememberLastSettings(value),
                  ),
                  SwitchListTile(
                    title: const Text('双击最大亮度'),
                    subtitle: const Text('双击开关按钮时设置为最大亮度'),
                    value: settings.doubleClickToMax,
                    onChanged: (value) => settings.setDoubleClickToMax(value),
                  ),
                  ListTile(
                    title: const Text('启动模式'),
                    subtitle: Text(_getStartupModeName(settings.startupMode)),
                    onTap: () => _showStartupModeDialog(context),
                  ),
                ],
              ),

              // 关于
              _buildSection(
                context,
                '关于',
                [
                  ListTile(
                    title: const Text('版本'),
                    subtitle: const Text('1.0.0'),
                  ),
                  ListTile(
                    title: const Text('开发者'),
                    subtitle: const Text('YuCheng @2024'),
                  ),
                ],
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSection(BuildContext context, String title, List<Widget> children) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
          child: Text(
            title,
            style: Theme.of(context).textTheme.titleMedium?.copyWith(
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
        ),
        ...children,
        const Divider(),
      ],
    );
  }

  String _getThemeModeName(ThemeMode mode) {
    switch (mode) {
      case ThemeMode.system:
        return '跟随系统';
      case ThemeMode.light:
        return '浅色';
      case ThemeMode.dark:
        return '深色';
    }
  }

  String _getStartupModeName(String mode) {
    switch (mode) {
      case 'last':
        return '恢复上次状态';
      case 'custom':
        return '自定义状态';
      case 'off':
        return '保持关闭';
      default:
        return '未知';
    }
  }

  // 基本设置对话框
  void _showDeviceNameDialog(BuildContext context) {
    final controller = TextEditingController(
      text: context.read<SettingsProvider>().deviceName,
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('设备名称'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            labelText: '名称',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              context.read<SettingsProvider>().setDeviceName(controller.text);
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showAutoOffDialog(BuildContext context) {
    final controller = TextEditingController(
      text: context.read<SettingsProvider>().autoOffMinutes.toString(),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('自动关闭时间'),
        content: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(
            labelText: '分钟',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final minutes = int.tryParse(controller.text);
              if (minutes != null && minutes > 0) {
                context.read<SettingsProvider>().setAutoOffMinutes(minutes);
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showThemeModeDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => SimpleDialog(
        title: const Text('主题'),
        children: [
          SimpleDialogOption(
            onPressed: () {
              context.read<SettingsProvider>().setThemeMode(ThemeMode.system);
              Navigator.pop(context);
            },
            child: const Text('跟随系统'),
          ),
          SimpleDialogOption(
            onPressed: () {
              context.read<SettingsProvider>().setThemeMode(ThemeMode.light);
              Navigator.pop(context);
            },
            child: const Text('浅色'),
          ),
          SimpleDialogOption(
            onPressed: () {
              context.read<SettingsProvider>().setThemeMode(ThemeMode.dark);
              Navigator.pop(context);
            },
            child: const Text('深色'),
          ),
        ],
      ),
    );
  }

  // 高级设置对话框
  void _showTransitionDurationDialog(BuildContext context) {
    final controller = TextEditingController(
      text: context.read<SettingsProvider>().transitionDuration.toInt().toString(),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('渐变持续时间'),
        content: TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(
            labelText: '毫秒',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final duration = double.tryParse(controller.text);
              if (duration != null && duration > 0) {
                context.read<SettingsProvider>().setTransitionDuration(duration);
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showBrightnessRangeDialog(BuildContext context) {
    final settings = context.read<SettingsProvider>();
    final minController = TextEditingController(
      text: (settings.minBrightness * 100).toInt().toString(),
    );
    final maxController = TextEditingController(
      text: (settings.maxBrightness * 100).toInt().toString(),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('亮度范围'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: minController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '最小亮度 (%)',
              ),
            ),
            TextField(
              controller: maxController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '最大亮度 (%)',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final min = double.tryParse(minController.text);
              final max = double.tryParse(maxController.text);
              if (min != null && max != null && min >= 0 && max <= 100 && min < max) {
                settings.setBrightnessRange(min / 100, max / 100);
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showColorTempRangeDialog(BuildContext context) {
    final settings = context.read<SettingsProvider>();
    final minController = TextEditingController(
      text: (settings.minColorTemp * 100).toInt().toString(),
    );
    final maxController = TextEditingController(
      text: (settings.maxColorTemp * 100).toInt().toString(),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('色温范围'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: minController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '最小色温 (%)',
              ),
            ),
            TextField(
              controller: maxController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '最大色温 (%)',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final min = double.tryParse(minController.text);
              final max = double.tryParse(maxController.text);
              if (min != null && max != null && min >= 0 && max <= 100 && min < max) {
                settings.setColorTempRange(min / 100, max / 100);
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showStartupModeDialog(BuildContext context) {
    final settings = context.read<SettingsProvider>();
    showDialog(
      context: context,
      builder: (context) => SimpleDialog(
        title: const Text('启动模式'),
        children: [
          SimpleDialogOption(
            onPressed: () {
              settings.setStartupSettings(mode: 'last');
              Navigator.pop(context);
            },
            child: const Text('恢复上次状态'),
          ),
          SimpleDialogOption(
            onPressed: () {
              settings.setStartupSettings(mode: 'custom');
              Navigator.pop(context);
              _showCustomStartupDialog(context);
            },
            child: const Text('自定义状态'),
          ),
          SimpleDialogOption(
            onPressed: () {
              settings.setStartupSettings(mode: 'off');
              Navigator.pop(context);
            },
            child: const Text('保持关闭'),
          ),
        ],
      ),
    );
  }

  void _showCustomStartupDialog(BuildContext context) {
    final settings = context.read<SettingsProvider>();
    final brightnessController = TextEditingController(
      text: (settings.startupBrightness * 100).toInt().toString(),
    );
    final colorTempController = TextEditingController(
      text: (settings.startupColorTemp * 100).toInt().toString(),
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('自定义启动状态'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: brightnessController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '亮度 (%)',
              ),
            ),
            TextField(
              controller: colorTempController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                labelText: '色温 (%)',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              final brightness = double.tryParse(brightnessController.text);
              final colorTemp = double.tryParse(colorTempController.text);
              if (brightness != null && colorTemp != null &&
                  brightness >= 0 && brightness <= 100 &&
                  colorTemp >= 0 && colorTemp <= 100) {
                settings.setStartupSettings(
                  brightness: brightness / 100,
                  colorTemp: colorTemp / 100,
                );
              }
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}
